package com.swak.converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.core.convert.converter.Converter;

import com.swak.utils.StringUtils;

/**
 * 转换 日期等
 * 
 * @author 618lf
 */
public class LocalDateTimeConverter implements Converter<String, LocalDateTime> {

	public static final String[] DATE_PATTERNS = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" };

	@Override
	public LocalDateTime convert(String source) {
		if (!StringUtils.isEmpty(source)) {
			String str = source.trim();

			/*
			 * 使用格式DATE_PATTERNS[1]
			 */
			if (str.length() > 10) {
				DateTimeFormatter df = DateTimeFormatter.ofPattern(DATE_PATTERNS[1]);
				return LocalDateTime.parse(str, df);
			}

			/*
			 * 使用格式DATE_PATTERNS[0]
			 */
			LocalDate localDate = LocalDate.parse(str, DateTimeFormatter.ofPattern(DATE_PATTERNS[0]));
			return localDate.atStartOfDay();
		}
		return null;
	}
}
